import { Component, Input, OnInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { FormGroup, FormBuilder } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

/**
 * 系统站内信接收人配置策略
 * @author xiaomin luo
 * @date 2019-12-03
 */
@Component({
  selector: 'msgmeta-strategy-modal',
  templateUrl: './strategy-modal.component.html',
  styles: [
    `
      .editable-tag {
        background: rgb(255, 255, 255);
        border-style: dashed;
      }
    `,
  ],
})
export class StragegySelectModalComponent implements OnInit, OnDestroy {
  @Input()
  record: any = {};
  @Input()
  title: string;
  @Input()
  view = false;

  users = [];
  roles = [];
  departs = [];
  loading = true;

  readonly = false;

  inputVisible1 = false;
  inputVisible2 = false;
  inputVisible3 = false;

  keyword1: any;
  keyword2: any;
  keyword3: any;

  options1: any[] = [];
  options2: string[] = [];
  options3: string[] = [];

  search1$ = new Subject<string>();
  search2$ = new Subject<string>();
  search3$ = new Subject<string>();

  constructor(public http: _HttpClient, private ref: NzModalRef) {}
  nzFilterOption = () => true;
  ngOnInit() {
    const { record } = this;
    if (record.isBroadcast === '1') {
      this.readonly = true;
    }
    this.http.get(`/cf/admin/web-msg/strategy/${record.id}`).subscribe(res => {
      this.loading = false;
      this.users = res.data.users;
      this.roles = res.data.roles;
      this.departs = res.data.departs;
    });
    this.search1$
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
        switchMap((q: string) => this.http.get(`/cf/admin/user/page`, { keyword: q, current: 1, size: 100 })),
      )
      .subscribe((res: any) => {
        this.options1 = res.data.records.map(r => {
          return { label: `${r.name + '(' + r.username + ')'}`, foreignId: r.userId };
        });
      });

    this.search2$
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
        switchMap((q: string) => this.http.get(`/cf/admin/role/page`, { q, current: 1, size: 100 })),
      )
      .subscribe((res: any) => {
        this.options2 = res.data.records.map(r => {
          return { label: `${r.roleName + '(' + r.roleCode + ')'}`, foreignId: r.roleId };
        });
      });

    this.search3$
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
        switchMap((q: string) => this.http.get(`/cf/admin/dept/page`, { q, current: 1, size: 100 })),
      )
      .subscribe((res: any) => {
        this.options3 = res.data.records.map(r => {
          return { label: `${r.name + '(' + r.deptCode + ')'}`, foreignId: r.deptId };
        });
      });
  }

  ngOnDestroy() {
    this.search1$.unsubscribe();
    this.search2$.unsubscribe();
    this.search3$.unsubscribe();
  }

  close() {
    this.ref.close();
  }

  handleClose(type, tag) {
    this.http.delete(`/cf/admin/web-msg/stragegy/${type}/${tag.foreignId}?metaId=${this.record.id}`).subscribe(res => {
      if (type === 'USER') {
        this.users = this.users.filter(t => t.foreignId !== tag.foreignId);
      } else if (type === 'ROLE') {
        this.roles = this.roles.filter(t => t.foreignId !== tag.foreignId);
      } else if (type === 'DEPART') {
        this.departs = this.departs.filter(t => t.foreignId !== tag.foreignId);
      }
    });
  }

  // 隐藏搜索框
  handleInputConfirm(type) {
    let foreignId = null;
    let obj = {};
    if (type === 'USER') {
      if (this.keyword1) {
        const count = this.users.filter(i => {
          return i.foreignId === this.keyword1.foreignId;
        }).length;
        if (count === 0) {
          foreignId = this.keyword1.foreignId;
          obj = this.keyword1;
        }
      }
    } else if (type === 'ROLE') {
      if (this.keyword2) {
        const count = this.roles.filter(i => {
          return i.foreignId === this.keyword2.foreignId;
        }).length;
        if (count === 0) {
          foreignId = this.keyword2.foreignId;
          obj = this.keyword2;
        }
      }
    } else if (type === 'DEPART') {
      if (this.keyword3) {
        const count = this.departs.filter(i => {
          return i.foreignId === this.keyword3.foreignId;
        }).length;
        if (count === 0) {
          foreignId = this.keyword3.foreignId;
          obj = this.keyword3;
        }
      }
    }
    if (foreignId) {
      this.http.post(`/cf/admin/web-msg/stragegy`, { type, metaId: this.record.id, foreignId }).subscribe(res => {
        if (res.status === 200) {
          if (type === 'USER') {
            this.users = [...this.users, obj];
          } else if (type === 'ROLE') {
            this.roles = [...this.roles, obj];
          } else if (type === 'DEPART') {
            this.departs = [...this.departs, obj];
          }
        }
      });
    }
    if (type === 'USER') {
      this.keyword1 = null;
      this.inputVisible1 = false;
    } else if (type === 'ROLE') {
      this.keyword2 = null;
      this.inputVisible2 = false;
    } else if (type === 'DEPART') {
      this.keyword3 = null;
      this.inputVisible3 = false;
    }
  }

  // 显示搜索框
  showInput(type): void {
    if (!this.readonly) {
      if (type === 'USER') {
        this.inputVisible1 = true;
      } else if (type === 'ROLE') {
        this.inputVisible2 = true;
      } else if (type === 'DEPART') {
        this.inputVisible3 = true;
      }
    }
  }

  // 搜索框有变动时触发
  onInputForUser(value: string) {
    this.search1$.next(value);
  }

  onInputForRole(value: string) {
    this.search2$.next(value);
  }

  onInputForDepart(value) {
    this.search3$.next(value);
  }
}
